﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using CMS.Web.Engine;

namespace CMS.Web.Data
{
    public interface IHostsRepository
    {
        IHostEntity GetHost(int ID);
        IHostEntity GetHost(string header, int port);
    }
    public class HostsRepository : IHostsRepository
    {
        private IEnumerable<IHostEntity> _hosts;      
        public HostsRepository() 
        {
            _hosts = XElement.Load(HttpContext.Current.Server.MapPath("~/Hosts.xml")).Elements("host").Select(x => (IHostEntity)new HostEntity
            {
                ID = x.AttributeValue<int>("ID"),
                Header = x.AttributeValue<string>("headerName"),
                Port = x.AttributeValue<int>("port")
            });
        }       
        public IEnumerable<IHostEntity> Hosts
        {
            get { return _hosts; }           
        }
        public IHostEntity GetHost(int ID)
        {
            return _hosts.SingleOrDefault(x => x.ID == ID);
        }
        public IHostEntity GetHost(string header, int port)
        {
            return _hosts.SingleOrDefault(x => x.Header.Equals(header, StringComparison.InvariantCultureIgnoreCase) && x.Port == port);
        }
    }   

    public class HostEntity : IHostEntity
    {
        public int ID { get; set; }
        public string Header { get; set; }
        public int Port { get; set; }
    }
}